package com.fhnew.app.model.internet.model;

import android.content.Context;
import android.os.Handler;

import com.fhnew.app.model.internet.HttpAPI;
import com.fhnew.app.model.internet.HttpRequest;
import com.fhnew.app.model.internet.been.B_AllThirdList;
import com.fhnew.app.model.internet.been.B_GameOver;
import com.fhnew.app.model.internet.been.B_ThirdMoneyList;
import com.fhnew.app.model.internet.been.B_UserMoney;
import com.fhnew.app.util.HLog;

import java.util.ArrayList;
import java.util.List;


public class ThirdGameModel {

    private static ThirdGameModel thirdGameModel;
    private UserModel userModel;

    private boolean isInitGameList = false;
    private B_ThirdMoneyList thirdGameList;//游戏金币的数据获取
    private boolean gameListRequesting = false;

    private B_AllThirdList allThirdList;//三方平台列表
    private List<ThirdGameMoneyChangedListener> thirdGameMoneyChangedListeners;

    private ThirdGameModel (Context context) {
        userModel = UserModel.getInstance(context);
        userModel.registListener(userInformationChanged);
        thirdGameMoneyChangedListeners = new ArrayList<>();

        init();
    }

    public static ThirdGameModel getInstance(Context context) {
        if (thirdGameModel == null) {
            thirdGameModel = new ThirdGameModel(context);
        }
        return thirdGameModel;
    }

    private void init(){
        refreshGameList();
        refreshAllThirdMoney();

        final Handler mHandler = new Handler();
        //每三秒获取余额和网络状态
        mHandler.post(new Runnable() {
            @Override
            public void run () {
                if (userModel.isLogin()) {
                    getUserMoney.startRequest(userModel.getToken());
                    mHandler.postDelayed(this, 8000);
                }
            }
        });
    }


    //==========================================================
    // 接口调用
    //==========================================================


    /**
     * 刷新所有三方平台金币
     */
    public void refreshAllThirdMoney () {
        if (userModel.isLogin()) {
            getAllThirdMoneyList.startRequest(userModel.getToken());
        }
    }

    /**
     * 获取三方平台列表
     * @return
     */
    public B_ThirdMoneyList getThirdGameList(){
        return thirdGameList;
    }

    /**
     * 刷新我的金币
     */
    public void refreshMyMoney(){
        getUserMoney.startRequest(userModel.getToken());
    }

    /**
     * 游戏下分并且刷新金币
     *
     * @param game_id
     */
    public void getThirdMoneyChange (int game_id) {
        getThirdGameMoney.startRequest(game_id, userModel.getToken());
    }

    /**
     * 单个游戏数据刷新
     * @param game_id
     */
    public void refreshThirdGameMoney(int game_id){
        getRefreshThirdGameMoney.startRequest(game_id,userModel.getToken());
    }

    public boolean isGameListRequesting(){
        return gameListRequesting;
    }

    /**
     * 获取指定游戏的金币
     *
     * @param game_id
     * @param refresh false 表示只获取本地缓存数据    true 表示先获取本地数的同时请求网络数据
     * @return
     */
    public String getMoney(int game_id, boolean refresh) {
        if (thirdGameList == null) return "-0.00";
        for (int i = 0; i < thirdGameList.getData().size(); i++) {
            if (thirdGameList.getData().get(i).getGame_id() == game_id) {
                if (refresh) {
                    refreshThirdGameMoney(thirdGameList.getData().get(i).getGame_id());
                }
                return thirdGameList.getData().get(i).getMoney() + "";
            }
        }
        return "";
    }


    /**
     * 注册事件
     * @param thirdGameMoneyChangedListener
     */
    public void registThirdGameMoneyChangedListener(ThirdGameMoneyChangedListener thirdGameMoneyChangedListener){
        this.thirdGameMoneyChangedListeners.add(thirdGameMoneyChangedListener);
    }

    /**
     * 注销事件
     * @param thirdGameMoneyChangedListener
     */
    public void unregistThirdGameMoneyChangedListener(ThirdGameMoneyChangedListener thirdGameMoneyChangedListener){
        this.thirdGameMoneyChangedListeners.remove(thirdGameMoneyChangedListener);
    }

    //=================================================================================
    //事件
    //==================================================================================

    /**
     * 刷新游戏列表
     */
    private void refreshGameList(){
        if (userModel.isLogin()) {
            getThirdGameList.startRequest(userModel.getToken());
        }
    }

    /**
     * 分发用户金币改变事件
     */
    private void notifyMyMoneyChanged(){
        for (int i = 0; i < thirdGameMoneyChangedListeners.size(); i++) {
            thirdGameMoneyChangedListeners.get(i).myMoneyChanged();
        }
    }

    /**
     * 分发三方平台金币改变事件
     */
    private void notifyAllThirdGameMoneyChanged (){
        for (int i = 0; i < thirdGameMoneyChangedListeners.size(); i++){
            thirdGameMoneyChangedListeners.get(i).allThirdGameMoneyChanged();
        }
    }

    /**
     * 分发指定平台金币改变事件
     * @param game_id
     */
    private void notifyThirdGameMoneyChanged(int game_id){
        for (int i = 0; i < thirdGameMoneyChangedListeners.size(); i++) {
            thirdGameMoneyChangedListeners.get(i).thirdGameMoneyChanged(game_id);
        }
    }

    private UserModel.UserInformationChanged userInformationChanged = new UserModel.UserInformationChanged() {

        @Override
        public void userInformationChanged () {
            if (isInitGameList == false && userModel.isLogin()) {
                init();
            }else{
                thirdGameList = null;
                isInitGameList = false;
            }

        }
    };

    public interface ThirdGameMoneyChangedListener {
        public void myMoneyChanged ();

        public void allThirdGameMoneyChanged ();

        public void thirdGameMoneyChanged(int game_id);
    }

    //=================================================================================
    //网络请求
    //==================================================================================

    //获取所有三方游戏列表
    private HttpAPI.GetThirdGameList getThirdGameList = new HttpAPI.GetThirdGameList() {

        @Override
        public void onStartedRequest (HttpRequest httpRequest) {
            super.onStartedRequest(httpRequest);
            gameListRequesting = true;
        }

        @Override
        public void result (B_AllThirdList result) {
            allThirdList = result;
            gameListRequesting =false;
        }

        @Override
        public void error (String msg) {
            gameListRequesting =false;
        }
    };

    //获取所有平台余额
    private HttpAPI.GetAllThirdMoneyList getAllThirdMoneyList = new HttpAPI.GetAllThirdMoneyList() {

        @Override
        public void result (B_ThirdMoneyList result) {
            thirdGameList = result;
            isInitGameList = true;
            notifyAllThirdGameMoneyChanged();
        }

        @Override
        public void error (String msg) {
            isInitGameList = false;
        }
    };

    //平台下分
    private HttpAPI.GetThirdGameMoney getThirdGameMoney = new HttpAPI.GetThirdGameMoney() {
        @Override
        public void result (B_GameOver result) {
            if (result.getCode() == 0) {
                new Handler().postDelayed(new Thread() {
                    @Override
                    public void run () {
                        super.run();
                        getRefreshThirdGameMoney.startRequest(result.getData().getGame_id(), userModel.getToken());
                    }
                }, 3000);
            } else {
                HLog.E("游戏下分接口调用失败 result");
            }
        }

        @Override
        public void error (String msg) {
            HLog.E("游戏下分接口调用失败" + msg);
        }
    };

    //获取单个游戏数据
    private HttpAPI.GetRefreshThirdGameMoney getRefreshThirdGameMoney = new HttpAPI.GetRefreshThirdGameMoney() {

        @Override
        public void result (B_GameOver result) {
            if (thirdGameList == null) {
                HLog.E(HLog.stackTrace() + "平台列表为空");
                return;
            }
            for (int i = 0; i < thirdGameList.getData().size(); i++) {
                if (result.getData().getGame_id()==thirdGameList.getData().get(i).getGame_id()) {
                    thirdGameList.getData().get(i).setMoney(result.getData().getMoney());
                    notifyThirdGameMoneyChanged(result.getData().getGame_id());
                }
            }
        }

        @Override
        public void error (String msg) {
            HLog.E(HLog.stackTrace()+"退出游戏时游戏分数刷新失败" + msg);
        }
    };

    //获取用户余额
    private HttpAPI.GetUserMoney getUserMoney = new HttpAPI.GetUserMoney(){
        @Override
        public void result (B_UserMoney result){
            if(result.getCode() == 0){
                userModel.getUser().setMoney(result.getData().getBalance());
                notifyMyMoneyChanged();
            }
        }

        @Override
        public void error (String msg){
            HLog.E(HLog.stackTrace()+"获取金币错误【"+msg+"】");
        }
    };

}
